package com.baoleme.controller;

import com.baoleme.common.Result;
import com.baoleme.entity.Orders;
import com.baoleme.entity.dto.OrderConditionalSearchDto;
import com.baoleme.entity.dto.OrderStatusDto;
import com.baoleme.entity.vo.OrderDetailVo;
import com.baoleme.exceptions.BusinessException;
import com.baoleme.exceptions.enumeration.ResponseEnum;
import com.baoleme.service.OrdersService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 订单表 前端控制器
 * </p>
 *
 * @since 2024-09-13
 */
@Slf4j
@RestController
@RequestMapping("/orders")
public class OrdersController {
    @Resource
    private OrdersService ordersService;

    /**
     * 修改订单状态
     * @param orderStatusDto 修改状态的Dto类
     * @return 是否修改成功
     */
    @PutMapping("modifyOrdersStatus")
    public Result<Boolean> modifyOrdersStatus(@RequestBody @Valid OrderStatusDto orderStatusDto) {
        idVerify(orderStatusDto.getId());
        return Result.success(ordersService.modifyOrdersStatus(orderStatusDto));
    }

    /**
     * 条件查询
     *
     * @param OrderConditionalSearchDto 查询条件Dto类，其中包含查询字段和分页查询用参数
     * @return 查询结果
     */
    @PostMapping("conditionSearch")
    public Result<IPage<Orders>> conditionSearch(@RequestBody @Valid OrderConditionalSearchDto OrderConditionalSearchDto) {
        if (OrderConditionalSearchDto == null) {
            throw new BusinessException(ResponseEnum.ILLEGAL_OPERATION);
        }
        return Result.success(ordersService.conditionSearch(OrderConditionalSearchDto));
    }

    /**
     * 查询各个状态订单数量
     *
     * @return 数量结果
     */
    @GetMapping("statistics")
    public Result<HashMap<String, Long>> statistics() {
        return Result.success(ordersService.statistics());
    }

    /**
     * 订单详情
     *
     * @param id 订单id
     * @return 查询结果
     */
    @GetMapping("details")
    public Result<OrderDetailVo> details(@RequestParam String id) {
        idVerify(id);
        return Result.success(ordersService.details(id));
    }

    @GetMapping("queryOrdersByUserId/{userId}")
    public Result<List<Orders>> queryOrdersByUserId(@PathVariable String userId) {
        idVerify(userId);
        return Result.success(ordersService.queryOrdersByUserId(userId));
    }


    /**
     * 订单id校验
     *
     * @param id 订单id
     */
    private void idVerify(String id) {
        try {
            Integer.parseInt(id);
        } catch (NumberFormatException e) {
            throw new BusinessException(ResponseEnum.ILLEGAL_OPERATION);
        }
    }


}
